﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.Web.UI.WebControls;
using NetDon.Utilities;
using SD.LLBLGen.Pro.ORMSupportClasses;
using SaleDiscount.Data;
using SaleDiscount.Data.CollectionClasses;
using SaleDiscount.Data.EntityClasses;
using SaleDiscount.Data.HelperClasses;
using SaleDiscount.Portal.eBay;
using eBay.Service.Core.Soap;

namespace SaleDiscount.Portal.Service
{
    public class SaleDiscountService
    {
        public EbayUserTokenEntity GetEbayUserToken(string ebayUserId)
        {
            var collection = new EbayUserTokenCollection();
            collection.GetMulti(EbayUserTokenFields.EBayUserId == ebayUserId);
            return collection.FirstOrDefault();
        }

        #region Trademark
        public int GetSaleDiscountCount(SaleDiscountCriteria criteria)
        {
            var collection = new SaleCollection();
            return int.Parse(collection.GetScalar(SaleFieldIndex.Id, null, AggregateFunction.CountDistinct, GetSearchSaleDiscountPredicate(criteria)).ToString());
        }

        private IPredicate GetSearchSaleDiscountPredicate(SaleDiscountCriteria criteria)
        {
            var expression = new PredicateExpression();
            //if (!string.IsNullOrEmpty(criteria.Name))
            //{
            //    expression.Add(HtmltooltrademarksettingFields.Name % ("%" + criteria.Name + "%"));
            //}

            return expression;
        }
        public SaleCollection SearchSaleDiscountByCondition(SaleDiscountCriteria criteria, string sortExpression, System.Web.UI.WebControls.SortDirection sortDirection, int pageSize, int pageIndex)
        {
            var sort = GetSaleDiscountSortExpression(sortExpression, sortDirection);
            var collection = new SaleCollection();
            collection.GetMulti(GetSearchSaleDiscountPredicate(criteria), 0, sort,
                              null, pageIndex + 1, pageSize);




            return collection;
        }
        private SortExpression GetSaleDiscountSortExpression(string strInput, SortDirection sortDirection)
        {
            SortExpression sort;
            switch (strInput)
            {
                case "SaleName":
                    sort = new SortExpression(SaleFields.SaleName | (SortOperator)(int)sortDirection);
                    break;
                case "StartDate":
                    sort = new SortExpression(SaleFields.StartDate | (SortOperator)(int)sortDirection);
                    break;
                case "EndDate":
                    sort = new SortExpression(SaleFields.EndDate | (SortOperator)(int)sortDirection);
                    break;
                default:
                    sort = new SortExpression
                               {
                                   SaleFields.StartDate | SortOperator.Ascending
                               };
                    sort.Add(new SortClause(SaleFields.SaleName, SortOperator.Ascending));
                    break;

            }
            return sort;
        }

        public bool RemoveSaleDiscount(int id)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "RemoveSaleDiscount");
            try
            {
                var removedItems = new ItemIDArrayType();
                removedItems.ItemID = new StringCollection();
                //delete 
                var saleListingCollection = new SaleListingsCollection();
                saleListingCollection.GetMulti(SaleListingsFields.SaleId == id);
                foreach (var saleListing in saleListingCollection)
                {
                    trans.Add(saleListing);
                    removedItems.ItemID.Add(saleListing.ItemId);
                    saleListing.Delete();
                }

                var sale = new SaleEntity(id);
                var promationSaleId = sale.PromotionSaleId;
                var promationSaleName = sale.SaleName;
                trans.Add(sale);
                sale.Delete();

                trans.Commit();
                if(promationSaleId.HasValue)
                {
                    var ebaySession = new eBaySession();
                    //remove them from eBay
                    if (saleListingCollection.Count > 0)
                    {
                       ebaySession.RemovePromotionalSaleListings(
                          promationSaleId.Value, removedItems);
                    }
                    ebaySession.SetPromotionalSale(ModifyActionCodeType.Delete, new PromotionalSaleType()
                                                                                    {
                                                                                        PromotionalSaleID = promationSaleId.Value,
                                                                                        PromotionalSaleName = promationSaleName
                                                                                    });
                }
        

            }
            catch (Exception)
            {
                trans.Rollback();

                throw;
            }
            return true;

        }
        #endregion

        public IEnumerable<ItemInfo>  LoadActiveListings(ItemInfoCriteria criteria, bool isGettingSellerList = true)
        {
            var items = isGettingSellerList ? new eBaySession().CallGetSellerList(DateTime.Now, DateTime.Now.AddDays(30)) : new eBaySession().GetActiveListings(GetListingTypeCodeType(criteria), GetItemSortTypeCodeType(criteria));
            foreach (ItemType item in items)
            {
                var itemInfo = new ItemInfo();
                itemInfo.ItemId = item.ItemID;
                itemInfo.PicitureURL = item.PictureDetails.GalleryURL;
                itemInfo.Title = item.Title;
                itemInfo.Qty = item.Quantity;
                itemInfo.ItemFormat = item.ListingType.ToString();
                itemInfo.EndDate = GetEndDate(item);
                itemInfo.ShippingCost = GetShippingCost(item.ShippingDetails);
                itemInfo.CurrentPrice = item.SellingStatus.CurrentPrice.currencyID.ToString() + " $" + item.SellingStatus.CurrentPrice.Value;
                yield return itemInfo;
            }
        }

        private DateTime GetEndDate(ItemType item)
        {
           ;
           return DateTime.Now.Add(System.Xml.XmlConvert.ToTimeSpan(item.TimeLeft));
        }
        private ItemSortTypeCodeType GetItemSortTypeCodeType(ItemInfoCriteria criteria)
        {
            return (ItemSortTypeCodeType)Enum.Parse(typeof(ItemSortTypeCodeType), criteria.SortBy);
        }


        private ListingTypeCodeType GetListingTypeCodeType(ItemInfoCriteria criteria)
        {
            return (ListingTypeCodeType)Enum.Parse(typeof(ListingTypeCodeType), criteria.ItemFormat);
        }

        private string GetShippingCost(ShippingDetailsType shippingDetails)
        {
            if(shippingDetails.ShippingServiceOptions.Count >0)
            {
                var firstShippingServiceOptions = shippingDetails.ShippingServiceOptions[0];
                if (firstShippingServiceOptions.FreeShipping)
                    return "Free";
                var shippingCost = string.Empty;
                if(firstShippingServiceOptions.ShippingServiceCost !=null)
                {
                    shippingCost += GetCurrencyString(firstShippingServiceOptions.ShippingServiceCost);
                }
                if (firstShippingServiceOptions.ShippingInsuranceCost != null)
                {
                    shippingCost += "<Br/>";
                    shippingCost += GetCurrencyString(firstShippingServiceOptions.ShippingInsuranceCost);
                }
                return shippingCost;
            }
            return string.Empty;
        }

        private string GetCurrencyString(AmountType amountType)
        {
            return amountType.currencyID.ToString() + " $" + amountType.Value;
        }

    }

    [Serializable]
    public class SaleDiscountCriteria
    {
        public string Name { get; set; }
    }

    public enum DiscountType
    {
        Fixed = 0,
        ByRatio
    }
       [Serializable]
    public class ItemInfoCriteria
    {
      
        public string keyword { get; set; }
       
        public string ItemFormat { get; set; }
        [DataMember]
        public string StoreCategoryId { get; set; }
        [DataMember]
        public string SortBy { get; set; }
        [DataMember]
        public Range<decimal?> CurrentPrice { get; set; }
    }

    [DataContract]
    public class ItemInfo
    {
        [DataMember]
        public string ItemId { get; set; }
        [DataMember]
        public string PicitureURL { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public string CurrentPrice { get; set; }
        [DataMember]
        public int Qty { get; set; }
        [DataMember]
        public string ShippingCost { get; set; }
        [DataMember]
        public string ItemFormat { get; set; }
        [DataMember]
        public DateTime EndDate { get; set; }
    }

}